package com.sanqing.iframe;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import com.sanqing.dao.Dao;
import com.sanqing.model.BookInfo;
import com.sanqing.model.Item;
import com.sanqing.model.MapPz;

public class BookSearchFrame extends JInternalFrame {
    private final BorderLayout borderLayout;
    private final JPanel mainPanel;
    private final BorderLayout borderLayout_1;
    private String[] columnNames;
    private JTable table;
    final JScrollPane scrollPane;
    private String ISBN = "222";
    private String Publisher;
    private double Price;
    private int PriceIndex;
    private String BookName;
    private String BookType;
    private String Author; // 新增：作者
    private String Translator; // 新增：译者
    private String Language; // 新增：语言
    private String searchType = "ISBN";
    final JComboBox searchComboBox;
    final JLabel searchCondition;
    final JTextField searchText;
    final GridLayout gridLayout;
    final JButton searchButton;
    private Object[][] results;
    private Map<Integer, Item> map = new HashMap<>();
    private JPopupMenu popupMenu; // 右键菜单

    private Object[][] getFileStates(List list) {
        String[] columnNames = { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格", "图书数量" };
        Object[][] results = new Object[list.size()][columnNames.length];
        for (int i = 0; i < list.size(); i++) {
            BookInfo bookinfo = (BookInfo) list.get(i);
            results[i][0] = bookinfo.getISBN();
            // 获取图书类型名称
            Integer typeId = bookinfo.getTypeid();
            // System.out.println(typeId);
            String bookTypeName = MapPz.getIdToName().get(typeId);
            // System.out.println(bookTypeName);
            results[i][1] = bookTypeName;
            results[i][2] = bookinfo.getBookname();
            results[i][3] = bookinfo.getWriter();
            results[i][4] = bookinfo.getTranslator();
            results[i][5] = bookinfo.getPublisher();
            results[i][6] = bookinfo.getDate();
            results[i][7] = bookinfo.getPrice();
            results[i][8] = bookinfo.getNumber();
        }
        return results;
    }

    public BookSearchFrame() {
        super();
        // 加入表格
        borderLayout = new BorderLayout();
        getContentPane().setLayout(borderLayout);
        setIconifiable(true);
        setClosable(true);
        setTitle("图书搜索");
        setBounds(100, 100, 593, 406);
        mainPanel = new JPanel();
        borderLayout_1 = new BorderLayout();
        borderLayout_1.setVgap(5);
        mainPanel.setLayout(borderLayout_1);
        mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
        getContentPane().add(mainPanel);
        scrollPane = new JScrollPane();
        mainPanel.add(scrollPane);

        // 初始化右键菜单
        initPopupMenu();

        // 加入查询条件
        final JPanel searchPanel = new JPanel();
        mainPanel.add(searchPanel, borderLayout.NORTH);
        searchComboBox = new JComboBox();
        searchComboBox.addItem("ISBN");
        searchComboBox.addItem("图书名称"); // 修正：原"图书姓名"改为"图书名称"
        searchComboBox.addItem("类别");
        searchComboBox.addItem("出版社");
        searchComboBox.addItem("作者"); // 新增：作者搜索
        searchComboBox.addItem("译者"); // 新增：译者搜索
        searchComboBox.addItem("语言"); // 新增：语言搜索
        searchComboBox.addItem("价格=");
        searchComboBox.addItem("价格>=");
        searchComboBox.addItem("价格>");
        searchComboBox.addItem("价格<=");
        searchComboBox.addItem("价格<");
        searchComboBox.addItemListener(new MyComboBox());// 注册下拉列表框监听器，判断是按照isdn还是图书姓名
        searchPanel.add(searchComboBox);
        searchCondition = new JLabel();
        searchCondition.setText("查询条件");
        gridLayout = new GridLayout(1, 3);
        // gridLayout.setVgap(5);
        gridLayout.setHgap(0);
        searchPanel.setLayout(gridLayout);
        searchPanel.add(searchCondition);
        searchPanel.add(searchComboBox);
        searchText = new JTextField("请输入要查询的信息");
        searchText.addFocusListener(new searchTextListener());
        searchText.addKeyListener(new searchKeyListener());
        searchPanel.add(searchText);
        searchButton = new JButton();
        searchButton.addActionListener(new searchButtonListener());// 注册搜索监听器
        searchButton.setText("查询");
        searchPanel.add(searchButton);
    }

    // 初始化右键菜单
    private void initPopupMenu() {
        popupMenu = new JPopupMenu();
        JMenuItem copyISBNItem = new JMenuItem("复制ISBN");
        copyISBNItem.addActionListener(e -> copySelectedRowISBN());
        popupMenu.add(copyISBNItem);

        // 新增右键菜单项
        JMenuItem copyBookNameItem = new JMenuItem("复制图书名称");
        copyBookNameItem.addActionListener(e -> copySelectedRowField(2));
        popupMenu.add(copyBookNameItem);

        JMenuItem copyCategoryItem = new JMenuItem("复制图书类别");
        copyCategoryItem.addActionListener(e -> copySelectedRowField(1));
        popupMenu.add(copyCategoryItem);

        JMenuItem copyAuthorItem = new JMenuItem("复制作者");
        copyAuthorItem.addActionListener(e -> copySelectedRowField(3));
        popupMenu.add(copyAuthorItem);

        JMenuItem copyTranslatorItem = new JMenuItem("复制译者");
        copyTranslatorItem.addActionListener(e -> copySelectedRowField(4));
        popupMenu.add(copyTranslatorItem);

        JMenuItem copyPublisherItem = new JMenuItem("复制出版商");
        copyPublisherItem.addActionListener(e -> copySelectedRowField(5));
        popupMenu.add(copyPublisherItem);

        JMenuItem copyLanguageItem = new JMenuItem("复制语言");
        copyLanguageItem.addActionListener(e -> copySelectedRowField(6));
        popupMenu.add(copyLanguageItem);
    }

    // 复制选中行的ISBN到剪贴板
    private void copySelectedRowISBN() {
        copySelectedRowField(0);
    }

    // 复制选中行的指定列数据到剪贴板
    private void copySelectedRowField(int columnIndex) {
        int selRow = table.getSelectedRow();
        if (selRow < 0) {
            JOptionPane.showMessageDialog(this, "请先选择一行数据", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String fieldValue = table.getValueAt(selRow, columnIndex).toString().trim();
        StringSelection selection = new StringSelection(fieldValue);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);

        String columnName = columnNames[columnIndex];
        JOptionPane.showMessageDialog(this, columnName + "已复制到剪贴板: " + fieldValue, "成功", JOptionPane.INFORMATION_MESSAGE);
    }

    class searchButtonListener implements ActionListener {// 查询按钮的监听器

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            if (searchText.getText().equals("请输入要查询的信息")) {
                JOptionPane.showMessageDialog(null, "未找输入任何查找的信息", "提示", JOptionPane.ERROR_MESSAGE);
            } else {
                // System.out.print(searchType);
                if (searchType.equals("ISBN")) {
                    // System.out.print(2);
                    ISBN = searchText.getText();
                    // System.out.print(ISBN);
                    results = getFileStates(Dao.selectBookInfo(ISBN));

                } else if (searchType.equals("图书名称")) // 修正：原"图书姓名"改为"图书名称"
                {
                    BookName = searchText.getText();
                    results = getFileStates(Dao.selectBookname(BookName));
                } else if (searchType.equals("类别")) {
                    BookType = searchText.getText();
                    results = getFileStates(Dao.selectBookCategory(BookType));
                } else if (searchType.equals("出版社")) {
                    Publisher = searchText.getText();
                    results = getFileStates(Dao.selectBookPublisher(Publisher));
                } else if (searchType.equals("作者")) // 新增：作者搜索逻辑
                {
                    Author = searchText.getText();
                    results = getFileStates(Dao.selectBookAuthor(Author));
                } else if (searchType.equals("译者")) // 新增：译者搜索逻辑
                {
                    Translator = searchText.getText();
                    results = getFileStates(Dao.selectBookTranslator(Translator));
                } else if (searchType.equals("语言")) // 新增：语言搜索逻辑
                {
                    Language = searchText.getText();
                    results = getFileStates(Dao.selectBookLanguage(Language));
                } else {
                    Price = Double.parseDouble(searchText.getText());
                    if (searchType.equals("价格="))
                        PriceIndex = 0;
                    else if (searchType.equals("价格>="))
                        PriceIndex = 1;
                    else if (searchType.equals("价格>"))
                        PriceIndex = 2;
                    else if (searchType.equals("价格<="))
                        PriceIndex = 3;
                    else if (searchType.equals("价格<"))
                        PriceIndex = 4;
                    // System.out.println(Price);
                    results = getFileStates(Dao.selectBookPrice(PriceIndex, Price));
                }
                tableR();
                if (results.length == 0) {
                    tableE();
                    JOptionPane.showMessageDialog(null, "未找到这本书", "提示", JOptionPane.ERROR_MESSAGE);
                }
            }
        }

    }

    class TableListener extends MouseAdapter {
        public void mouseClicked(final MouseEvent e) {
            // 处理左键点击显示详情
            if (e.getButton() == MouseEvent.BUTTON1) {
                int selRow = table.rowAtPoint(e.getPoint());
                if (selRow >= 0) {
                    table.setRowSelectionInterval(selRow, selRow);
                    showBookDetails(selRow);
                }
            }
            // 处理右键点击显示菜单
            else if (e.getButton() == MouseEvent.BUTTON3) {
                int selRow = table.rowAtPoint(e.getPoint());
                if (selRow >= 0) {
                    table.setRowSelectionInterval(selRow, selRow);
                    popupMenu.show(table, e.getX(), e.getY());
                }
            }
        }

        // 显示图书详情
        private void showBookDetails(int selRow) {
            StringBuilder details = new StringBuilder();
            details.append("图书编号: ").append(table.getValueAt(selRow, 0)).append("\n");
            details.append("图书类别: ").append(table.getValueAt(selRow, 1)).append("\n");
            details.append("图书名称: ").append(table.getValueAt(selRow, 2)).append("\n");
            details.append("作者: ").append(table.getValueAt(selRow, 3)).append("\n");
            details.append("译者: ").append(table.getValueAt(selRow, 4)).append("\n");
            details.append("出版商: ").append(table.getValueAt(selRow, 5)).append("\n");
            details.append("出版日期: ").append(table.getValueAt(selRow, 6)).append("\n");
            details.append("价格: ").append(table.getValueAt(selRow, 7)).append("\n");
            details.append("图书数量: ").append(table.getValueAt(selRow, 8)).append("\n");

            JOptionPane.showMessageDialog(null, details.toString(), "图书详情", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    class MyComboBox implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent arg0) {
            // TODO Auto-generated method stub
            searchType = (String) arg0.getItem();
            searchText.setText("请输入要查询的信息");
            // System.out.println(searchType);

        }
    }

    class searchTextListener implements FocusListener {

        @Override
        public void focusGained(FocusEvent arg0) {
            // TODO Auto-generated method stub
            // System.out.println(searchText.getName());
            if (searchText.getText().equals("请输入要查询的信息"))
                searchText.setText("");
        }

        @Override
        public void focusLost(FocusEvent arg0) {
            // TODO Auto-generated method stub
            if (searchText.getText().equals(""))
                searchText.setText("请输入要查询的信息");

        }
    }

    class searchKeyListener implements KeyListener {

        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub
            if (arg0.getKeyCode() == 10)
                searchButton.doClick();

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub
            if (searchType.equals("ISBN") && searchText.getText().length() > 13) {
                searchText.setText(searchText.getText().substring(0, 13));
                String a = searchText.getText();
            }
            if (searchType.equals("ISBN")) {
                String a = searchText.getText();
                for (int i = 0; i < a.length(); i++) {
                    int b = a.charAt(i);
                    if (!(b <= 57 && b >= 48)) {
                        searchText.setText("");
                        break;
                    }
                }
            }

        }

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
            if (searchType.equals("ISBN")) {
                int temp = e.getKeyChar();
                if (searchText.getText().length() == 13) {
                    e.consume();
                } else {
                    if (temp == 10) {
                    } else if (temp != 46) {
                        if (temp != 8) {
                            if (temp > 57) {
                                e.consume();
                            } else if (temp < 48) {
                                e.consume();
                            }
                        }
                    } else {
                        e.consume();
                    }
                }
            } else if (searchType.indexOf("价格") == 0) {
                int temp = e.getKeyChar();
                if (temp == 10) {

                } else if (temp != 46) {
                    if (temp != 8) {
                        if (temp > 57) {
                            e.consume();
                        } else if (temp < 48) {
                            e.consume();
                        }
                    }
                }
            }
        }

    }

    private void tableR()// 更新表
    {
        columnNames = new String[] { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格", "图书数量" }; // 正确声明
        table = new JTable(results, columnNames);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrollPane.setViewportView(table);
        table.addMouseListener(new TableListener());
    }

    private void tableE()// 清空表的内容
    {
        columnNames = new String[0]; // 正确声明
        table = new JTable(results, columnNames);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrollPane.setViewportView(table);
        table.addMouseListener(new TableListener());
    }
}